package com.ffx.servlet;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ffx.pojo.Student;
import com.ffx.service.StudentService;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @outhor fufeixiang
 * @date 2021-11-09
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {


    private StudentService studentService;
    @Override
    public void init() throws ServletException {
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        studentService =  wac.getBean(StudentService.class);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String cmd = req.getParameter("cmd");
        if(StrUtil.isNotBlank(cmd)){
            if("list".equals(cmd)){
                list(req,resp);
            }
        }

    }

    //学生列表
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //查找所有学生
        List<Student> studentList =  studentService.findAll();
        //转换为json对象并输出
        resp.getWriter().println(JSON.toJSONString(studentList));
        resp.getWriter().flush();

    }
}
